<?php
/**
 * User: bgl
 * Date: 2023/3/15
 * Time: 4:14
 */

namespace App\Admin\Controllers\KolManage;


use App\Admin\Ajax\KolManage\KolOrderAjax;
use App\Admin\Controllers\ErpController;
use App\Models\KolManage\Kol;
use App\Models\KolManage\KolOrder;
use App\Util\RExcel;
use Encore\Admin\Layout\Content;
use Illuminate\Support\Facades\Request;

class KolOrderController extends ErpController{

    protected $title = 'Kol红人订单';

    protected $filters = [
        'order_no' => null,
        'kol_id' => null,
    ];

    protected function grid()
    {
        $filters = $this->getFilters();
        $this->initFilters($filters);
        $query = $this->_initQuery($filters);
        $paginator = $this->paginator($query);
        $action = $this->getAction();
        $filtersBlade = [];
        $filtersBlade['order_no'] = $this->filters['order_no'];
        $filtersBlade['kol_id'] = getOptions(Kol::options(), $this->filters['kol_id']);

        $downloadUrl = $this->getDownloadUrl('/xqc/kol-manage/kol-order-download');

        return view('kol-manage.kol-order.list.index', compact('paginator','action','filtersBlade','downloadUrl'));
    }

    private function _initQuery($filters){
        $query = KolOrder::query()->orderBy('id', 'DESC');
        foreach ($filters as $field => $filter){
            if(!$filter)continue;

            if($field == 'order_no'){
                $query->where('order_no',$filter);
            }

            if(in_array($field,['order_no','kol_id'])){
                $query->where($field,$filter);
            }
        }
        return $query;
    }

    public function create(Content $content){

        return $content
            ->title($this->title())
            ->description($this->description['create'] ?? trans('admin.create'))
            ->body(view('kol-manage.kol-order-create.index'));
    }

    public function update($id){

        try{
            list($class,$name) = explode('-',Request::get('name'));
            $value = Request::get('value');
            $model = KolOrder::query()->find($id);
            $model->{$name} = $value;
            if(!$model->save()){
                return response()->json(['status' => false, 'message' => '操作失败']);
            }else{
                return response()->json(['status' => true, 'message' => '操作成功']);
            }
        }catch (\Exception $e){
            report($e);
            return response()->json(['status' => false, 'message' => '系统异常！']);
        }
    }

    public function modal(){
        $action = request('action');
        $param = request('param');

        $modal = new KolOrderAjax();
        return $param ? call_user_func([$modal,$action],$param) : call_user_func([$modal,$action]);
    }

    public function ajax(){
        $action = request('action');
        $param = request('param');
        $ajax = new KolOrderAjax();
        return $param ? call_user_func([$ajax,$action],$param) : call_user_func([$ajax,$action]);
    }

    public function download(){
        $filters = $this->getFilters();
        $query = $this->_initQuery($filters);
        $this->_exeDownload($query);
    }

    private function _exeDownload($query){
        $head = ['订单号','kol红人账号','备注'];
        RExcel::exportCsv('kol红人订单', function () use ($head, $query) {
            $fp = fopen('php://output', 'w');
            fwrite($fp, chr(0xEF).chr(0xBB).chr(0xBF));
            fputcsv($fp, $head);
            $query->chunk(1000, function ($re) use ($fp){
                $data = KolOrder::getDownloadData($re);
                foreach ($data as $item) {
                    fputcsv($fp, $item);
                }
            });
        });
    }

    /*protected function form(){

        $form = new Form(new KolOrder());

        $form->tools(function (Form\Tools $tools){
            $tools->disableView();
        });

        $form->hidden('id');
        $form->select('kol_id', 'kol账号')->options(Kol::options())->required()->rules("required")->setWidth(5);
        $form->text('order_no', '订单号')->setWidth(5);
        $form->textarea('remark', '备注')->setWidth(5);
        $form->hidden('admin_id')->value(Admin::user()->id);

        $form->divider();

        if($form->isCreating()){
            $form->disableCreatingCheck(false);
        }
        $form->saving(function (Form $form) {

            // 判断是否是新增操作
            if ($form->isCreating()) {
                $count = KolOrder::query()
                    ->where('id', '<>', $form->model()->id)
                    ->where('order_no', $form->order_no)
                    ->count();
                if($count > 0){
                    admin_error('重复添加', '该订单号已存在');
                    return back()->withInput();
                }
            }else{
                $count = KolOrder::query()
                    ->where('id', '<>', $form->model()->id)
                    ->where('order_no', $form->order_no)
                    ->count();
                if($count > 0){
                    admin_error('重复添加', '该订单号已存在');
                    return back()->withInput();
                }
            }
        });

        $form->tools(function (Form\Tools $tools) {
            $tools->disableDelete();
        });
        return $form;
    }*/

}